<template>
  <div class="nav-br">
    <page-box class="serveNo">
      <template #top>
        <alert-msg
          content="可自定义企业自己的小休电话条状态，员工工作时可以根据实际情况切换，系统自动记录。注意只有“空闲”状态才会被分配话务，非建议设置修改在非上班时间进行"
        >
          <template #icon>
            <i class="MC_iconfont MC_icon-xinxi-mian"></i>
          </template>
        </alert-msg>
      </template>
      <template #search>
        <search-form :fieldList="fieldList" :form="form" @onSearchFun="searchFun"></search-form>
      </template>
      <template #btn>
        <el-button @click="searchFun">查询</el-button>
        <el-button type="primary" @click="add">新建</el-button>
      </template>
      <template #table>
        <resize-table
          :topHeight="50"
          :headers="tableHeaders"
          :data="tableData"
          :pagingData="pagingData"
          @onPageChange="handleCurrentChange"
          @onPageSizeChange="handleSizeChange"
          @onCheckHeadersChange="checkHeadersChange"
        >
          <template #status="{ scope }">
            <el-switch
              v-model="scope.row.status"
              active-value="enable"
              inactive-value="disable"
              :disabled="scope.row.system"
              @change="statusChange(scope.row)"
              class="ml-2"
              inline-prompt
            />
          </template>
          <template #oprate="{ scope }">
            <el-button
              v-if="!(scope.row.name == '忙碌' || scope.row.name == '空闲')"
              @click="edit(scope.row)"
              type="text"
            >
              编辑
            </el-button>
            <el-button
              v-if="!(scope.row.name == '忙碌' || scope.row.name == '空闲')"
              @click="del(scope.row)"
              type="text"
              >删除
            </el-button>
          </template>
        </resize-table>
      </template>
    </page-box>
    <resize-drawer
      :title="drawerName"
      :drawer="drawerShow"
      :size="576"
      :isShowMoreBtn="true"
      @onCloseDraw="closeDraw"
      @onSave="save"
      @onCancelFun="cancelFun"
    >
      <template #column>
        <el-form ref="userFormRef" :model="drawerForm" :rules="drawerRules" label-position="top" class="demo-userForm">
          <el-form-item prop="name">
            <template #label>
              <span>电话条状态 <span class="label-tip">至多10个字，建议控制在2～3个字</span></span>
            </template>
            <el-input v-model.trim="drawerForm.name" maxlength="10" placeholder="请输入"> </el-input>
          </el-form-item>
          <!-- <el-form-item label="类型" prop="type">
            <el-select :disabled="!isAdd" v-model="drawerForm.type" class="m-2" placeholder="请选择">
              <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item> -->
        </el-form>
      </template>
    </resize-drawer>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, getCurrentInstance, markRaw } from 'vue'
import ResizeDrawer from '@/common/components/resize-drawer/index.vue'
import ResizeTable from '@/common/components/resize-table/index.vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { fetchData, clientDelete, clientUpdateSave, clientAddSave } from '@app/call-center/apis/client-state'
import { deepClone } from '@/common/utils/common'
import alertMsg from '@common/components/alert/index.vue'
import searchForm from '@/common/components/base-form/form.vue'
import pageBox from '@common/components/page-box.vue'
import { commonStore } from '@/common/store/modules/common'
import deleteIcon from '@/common/components/delete-icon/index.vue'
export default defineComponent({
  name: 'HomeView',
  components: {
    ResizeDrawer,
    ResizeTable,
    alertMsg,
    searchForm,
    pageBox
  },
  setup() {
    const state = reactive({
      drawerName: '编辑电话条状态',
      drawerShow: false,
      isAdd: false,
      drawerForm: {
        name: '',
        type: '自定义',
        isSystem: 0,
        status: 'enable',
        number: null
      },
      // searchForm: {
      //   name: 'Hello',
      //   status: ''
      // },
      fieldList: [
        {
          name: '电话条状态',
          field: 'name',
          type: 'text'
        },
        {
          name: '状态',
          field: 'status',
          type: 'dropdown',
          choices: [
            {
              // 状态列表
              label: '全部',
              value: ''
            },
            {
              // 状态列表
              label: '启用',
              value: 'enable'
            },
            {
              // 状态列表
              label: '停用',
              value: 'disable'
            }
          ]
        }
      ],
      form: { name: '', status: '' },
      statusList: [
        {
          // 状态列表
          label: '自定义',
          value: '自定义'
        }
      ],
      tableHeaders: [
        { label: '电话条状态', prop: 'name', show: true },
        { label: '类型', prop: 'type', show: true },
        { label: '最后更新时间', prop: 'updateTime', show: true },
        { label: '最后操作人', prop: 'agentName', show: true },
        { label: '状态', prop: 'status', show: true, custom: true },
        { label: '操作', prop: 'oprate', show: true, width: 160 }
      ],
      tableData: [
        {
          name: '空闲',
          type: '系统设置',
          status: true
        },
        {
          name: '忙碌',
          type: '系统设置',
          status: 0
        },
        {
          name: '午休',
          type: '自定义',
          status: 1
        }
      ],
      tempList: [], //表格原始数据
      drawerRules: {
        name: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      pagingData: {
        page: 1,
        total: 200,
        limit: 10
      }
    })

    const closeDraw = () => {
      state.drawerShow = false
    }

    const cancelFun = () => {
      state.drawerShow = false
    }

    function openDraw() {
      state.drawerShow = true // 抽屉
    }
    //添加
    function add() {
      state.drawerName = '添加电话条状态'
      state.isAdd = true
      state.drawerShow = true // 抽屉
      state.drawerForm = { name: '', type: '自定义', isSystem: 0, status: 'enable', number: null }
    }
    //编辑
    function edit(row: any) {
      state.drawerName = '编辑电话条状态'
      state.isAdd = false
      state.drawerShow = true // 抽屉
      state.drawerForm = {
        name: row.name,
        type: row.type,
        isSystem: row.isSystem,
        status: row.status,
        number: row.number
      }
    }
    function del(row: any) {
      ElMessageBox.confirm('此操作将永久删除, 是否继续?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
        icon: markRaw(deleteIcon)
      }).then(() => {
        clientDelete({ number: row.number }).then((res) => {
          if (res.success) {
            ElMessage({ message: '删除成功', type: 'success' })
            callList('refresh')
          }
        })
      })
    }
    const instance: any = getCurrentInstance()
    //保存
    function save() {
      instance?.refs.userFormRef.validate((valid: boolean) => {
        if (valid) {
          if (state.isAdd) {
            clientAddSave(state.drawerForm).then((res) => {
              if (res.success) {
                callList()
                ElMessage({ message: '保存成功', type: 'success' })
                state.drawerShow = false
              }
            })
          } else {
            clientUpdateSave(state.drawerForm).then((res) => {
              if (res.success) {
                callList()
                ElMessage({ message: '修改成功', type: 'success' })
                state.drawerShow = false
              }
            })
          }
        }
      })
    }
    function handleCurrentChange(page: number) {
      state.pagingData.page = page
      callList()
    }

    function handleSizeChange(size: number) {
      state.pagingData.limit = size
      callList()
    }
    //列表状态切换
    function statusChange(row: any) {
      if (row.status && row.number) {
        const status = row.status == 'enable' ? '启用' : '停用'
        ElMessageBox.confirm(`确定要${status}${row.name}吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            clientUpdateSave({ status: row.status, number: row.number }).then((res) => {
              if (res.success) {
                callList()
                ElMessage({ message: '操作成功', type: 'success' })
              }
            })
          })
          .catch(() => {
            callList()
          })
      }
    }
    //获取表格数据
    function callList(refresh?: any) {
      const sendData = {
        ...state.form,
        pageSize: state.pagingData.limit,
        page: state.pagingData.page
      }
      fetchData(sendData).then((res) => {
        if (res.success) {
          const list = res.data.list || []
          list.forEach((item: any) => {
            item.type = item.system ? '系统默认' : '自定义'
            const agentObj = (commonStore().publicCache.userCacheObj as any)[item.updateUser]
            item.agentName = agentObj ? agentObj.name : '--'
          })
          state.tempList = list
          state.tableData = list
          state.pagingData.total = res.data.page.total || 0
          // if (refresh) {
          //   // 编辑，停用，启用，删除，重新更新一下前台检索的数据
          //   searchFun()
          // }
        }
      })
    }
    function searchFun() {
      state.pagingData.page = 1
      callList()
    }
    const checkHeadersChange = (checkList: any) => {
      state.tableHeaders = checkList
    }
    onMounted(() => {
      callList()
    })

    return {
      ...toRefs(state),
      closeDraw,
      openDraw,
      cancelFun,
      handleCurrentChange,
      handleSizeChange,
      checkHeadersChange,
      edit,
      del,
      add,
      save,
      searchFun,
      statusChange,
      callList
    }
  }
})
</script>
<style lang="stylus" scoped>
.nav-br
  :deep(.serveNo)
    .box
      padding 24px 0px
.label-tip
    font-weight: 400;
    font-size: 12px;
    line-height: 18px;
    letter-spacing: 0.001em;
    color: rgba(0, 0, 0, 0.38);
.nav-br {
  .serch-box {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ecf0f3;

    .serch-list {
      display: flex;
    }

    .serch-oprate {
      display: flex;
    }
  }
}
</style>
